package com.to_door_recycle.user_wxapp.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.to_door_recycle.common.util.ExceptionUtil;
import com.to_door_recycle.dao.IUserDao;
import com.to_door_recycle.model.dto.AuthDto;
import com.to_door_recycle.model.pojo.User;
import com.to_door_recycle.user_wxapp.service.IUserAuthService;
import com.to_door_recycle.user_wxapp.util.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@Service
public class UserAuthServiceImpl implements IUserAuthService {

    @Resource
    private IUserDao userDao;

    @Override
    public String register(AuthDto authDto) {
        User user = null;
        //  openid注册
        if (StringUtils.isNotBlank(authDto.getWxLoginCode())) {
            String openid = WechatUtil.getOpenId(authDto.getWxLoginCode());
            //  生成一个用户名
            String username = random6BitUsername();
            //  封装用户信息
            user = User.builder()
                    .openid(openid)
                    .username(username)
                    .avatar(authDto.getAvatar())
                    .nickname(authDto.getNickname())
                    .build();
        } //    手机号注册
        else {
            //  1.校验手机号
            //      判断手机号是否为空以及是否正确
            ExceptionUtil.throwAuthExceptionIf(StringUtils.isBlank(authDto.getPassword()) || !authDto.getPhone().matches("0?(13|14|15|18|17)[0-9]{9}"), "手机号错误");
            //      判断手机号是否注册过
            ExceptionUtil.throwAuthExceptionIf(Objects.nonNull(userDao.selectByPhone(authDto.getPhone())), "该手机号已经注册过");

            //  2.校验密码
            //      校验两次密码是否一致
            ExceptionUtil.throwAuthExceptionIf(!StringUtils.equals(authDto.getPassword(), authDto.getConfirmPassword()), "两次密码输入不一致");
            //      校验密码长度
            ExceptionUtil.throwAuthExceptionIf(StringUtils.isBlank(authDto.getPassword()) || authDto.getPassword().length() < 4, "密码长度不能低于4位");

            //  3.随机生成6位数的唯一用户名
            String username = random6BitUsername();

            //  4.封装用户信息
            user = User.builder()
                    .phone(authDto.getPhone())
                    .username(username)
                    .password(authDto.getPassword())
                    .build();
        }
        //  4.向数据库中添加用户
        userDao.save(user);
        //  5.登录
        //      记录登录状态，返回token
        StpUtil.login(user.getUsername());

        //  返回登录标识token
        return StpUtil.getTokenValue();
    }

    private String random6BitUsername() {
        while (true) {
            String username = RandomUtil.randomInt(100000, 999999) + "";
            if (Objects.isNull(userDao.selectByUsername(username))) {
                return username;
            }
        }
    }

    @Override
    public String login(AuthDto authDto) {

        User user = null;
        //  一键登录
        if (StringUtils.isNotBlank(authDto.getWxLoginCode())) {
            //  获取openid
            String openid = WechatUtil.getOpenId(authDto.getWxLoginCode());
            //  校验微信临时登录码是否失效
            ExceptionUtil.throwAuthExceptionIf(StringUtils.isBlank(openid),"微信登录临时凭证已失效");
            //  判断用户是否存在
            user = userDao.selectByOpenId(openid);
            if (user == null) {
                //  生成一个用户名
                String username = random6BitUsername();
                //  注册用户
                user = User.builder()
                        .openid(openid)
                        .username(username)
                        .avatar(authDto.getAvatar())
                        .nickname(authDto.getNickname())
                        .build();
                userDao.save(user);
            }
        } else {
            //  手机号登录
            //      判断手机号是否为空以及是否正确
            if (StringUtils.isNotBlank(authDto.getPassword()) && authDto.getPhone().matches("0?(13|14|15|18|17)[0-9]{9}")) {
                user = userDao.selectByPhoneAndPassword(authDto.getPhone(), authDto.getPassword());
            } //  用户名登录
            else if (StringUtils.isNotBlank(authDto.getUsername()) && authDto.getUsername().length() >= 6 ){
                user = userDao.selectByUsernameAndPassword(authDto.getUsername(), authDto.getPassword());
            }
            //  2.校验用户是否存在
            ExceptionUtil.throwAuthExceptionIf(user == null, "用户不存在");
        }

        //  3.记录登录状态
        StpUtil.login(user.getUsername());

        //  4.返回生成的token
        return StpUtil.getTokenValue();
    }

}
